const FILES_PATH = require("./filesPathConfigs"),//文件夹路径对象
    // 导入controller (处理业务逻辑的 )      middleware(中间件):
    controllerMiddleware   = require(FILES_PATH.controllerMiddlewarePath);

var express         = require('express'),
	path            = require('path'),
	favicon         = require('serve-favicon'),
	cookieParser    = require('cookie-parser'),
	bodyParser      = require('body-parser');

//数据库
var mysql = require("mysql"),
    mysqlConnection = require("express-myconnection"),
    mysqlConfigs =  require(FILES_PATH.mysqlServiceConfigPath);

//日志
var     log4js          = require('log4js');
//日志级别(从高到低的级别):OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
//Log4j建议只使用四个级别，优先级从高到低分别是 ERROR、WARN、INFO、DEBUG
//用法：
// var log = require('./util/logger').getLogger("system");
// log.error("输出错误日志");
//日志输出模式见配置文件
//"systemLog": {
//"type": "dateFile",
//    "filename": "logs/access.log",
//    "pattern": "-yyyy-MM-dd",
//    "alwaysIncludePattern": false
//}
var log = require('./util/logger').getLogger("system");
var app = express();

//解决跨域：allow custom header and CORS
app.all('*',function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
  res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');

  if (req.method == 'OPTIONS') {
    res.sendStatus(200); /*让options请求快速返回*/
  }
  else {
    next();
  }
});


// view engine setup
app.set('views', FILES_PATH.viewsPath);
app.set('view engine', 'ejs');

// 数据库连接:将方法绑定到req上;
app.use(mysqlConnection(mysql,mysqlConfigs,"pool"));


// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(log4js.connectLogger(log4js.getLogger("express")));
//日志输出测试
log.error("我在测试输出日志是否正常！！！");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(FILES_PATH.staticsPath));

//routers
app.use(controllerMiddleware(FILES_PATH.controllersFatherPath));//APIs


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});





module.exports = app;
